# --- Logging setup ---
$logDir  = "C:\ProgramData\FileWaveRename"
$logFile = Join-Path $logDir "rename.log"
if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }

function Write-Log {
    param([string]$Message, [string]$Level = "INFO")
    $line = "{0} [{1}] {2}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level, $Message
    Add-Content -Path $logFile -Value $line
}

Write-Log "===== Script start ====="
Write-Log "Running as: $([Security.Principal.WindowsIdentity]::GetCurrent().Name)"
Write-Log "64-bit process: $([Environment]::Is64BitProcess) | PS version: $($PSVersionTable.PSVersion)"

$partOfDomain = (Get-CimInstance Win32_ComputerSystem).PartOfDomain
Write-Log "Domain joined: $partOfDomain"

# --- Read registry (try both views) ---
$subKey    = "SOFTWARE\FileWave\WinClient"
$valueName = "fwUser"
$fwClientName = $null

foreach ($view in @([Microsoft.Win32.RegistryView]::Registry32, [Microsoft.Win32.RegistryView]::Registry64)) {
    try {
        $base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $view)
        $key  = $base.OpenSubKey($subKey)
        if ($null -eq $key) {
            $key = $base.OpenSubKey("SOFTWARE\WOW6432Node\FileWave\WinClient")
        }
        if ($null -eq $key) { Write-Log "Key not found in $view view" "WARN"; continue }

        Write-Log "Key found in $view view. Values present:"
        foreach ($n in $key.GetValueNames()) { Write-Log "   $n = '$($key.GetValue($n))'" }

        $val = $key.GetValue($valueName)
        if ($val) { $fwClientName = "$val".Trim(); Write-Log "Using '$valueName' = '$fwClientName' from $view view"; break }
    } catch {
        Write-Log "Registry read failed in $view view: $_" "ERROR"
    }
}

if (-not $fwClientName) {
    Write-Log "Could not obtain '$valueName' from registry." "ERROR"
    exit 1
}

# --- Validate name ---
if ($fwClientName.Length -gt 15 -or $fwClientName -match '[\\/:*?"<>|,~!@#$%^&''(){}_ .]' -or $fwClientName -match '^\d+$') {
    Write-Log "'$fwClientName' is not a valid NetBIOS computer name (max 15 chars, no spaces/special chars/dots, not all digits)." "ERROR"
    exit 4
}

# --- Compare against active AND pending name ---
$activeName  = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName").ComputerName
$pendingName = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName").ComputerName
Write-Log "Active name: $activeName | Pending name: $pendingName | Desired: $fwClientName"

if ($fwClientName -ieq $activeName) {
    Write-Log "Name already correct. Nothing to do."
    exit 0
}
if ($fwClientName -ieq $pendingName) {
    Write-Log "Rename already pending; reboot required. Not renaming again."
    exit 0
}

# --- Rename ---
try {
    Write-Log "Renaming '$activeName' -> '$fwClientName'"
    Rename-Computer -NewName $fwClientName -Force -ErrorAction Stop
    Write-Log "Rename-Computer succeeded. Scheduling reboot."
    shutdown.exe /r /t 60 /c "Computer renamed to $fwClientName. Rebooting in 60 seconds." /f /d p:4:1
    Write-Log "shutdown.exe exit code: $LASTEXITCODE"
    exit 2
} catch {
    Write-Log "Rename-Computer FAILED: $($_.Exception.Message)" "ERROR"
    Write-Log "Full error: $($_ | Out-String)" "ERROR"
    exit 3
}